package com.zhss.demo.register.server;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 心跳计数器
 *
 * @author: gubatian
 * @create: 2021-09-23 11:36
 */
public class HeartbeatCounter {
    /**
     * 单例
     */
    private static HeartbeatCounter instance = new HeartbeatCounter();
    /**
     * 最近一次心跳总数
     */
    private AtomicLong latestMinuteHeartbeatRate = new AtomicLong(0L);
    /**
     * 最近一分钟时间戳
     */
    private long latestMinuteTimestamp = System.currentTimeMillis();
    /**
     * 后台线程
     */
    private Daemon daemon;
    private HeartbeatCounter() {
        daemon = new Daemon();
        daemon.setDaemon(true);
        daemon.start();
    }

    public static HeartbeatCounter getInstance() {
        return instance;
    }

    /**
     * 心跳累计
     */
    public void increment() {
        latestMinuteHeartbeatRate.incrementAndGet();
    }

    /**
     * 获取最近一分钟心跳次数
     * @return
     */
    public long get() {
        return latestMinuteHeartbeatRate.get();
    }
    /**
     * 后台线程
     * 每隔一秒查看最近一次心跳是否超过60秒
     */
    private class Daemon extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    long currentTime = System.currentTimeMillis();
                    // 当前时间超过最近一分钟
                    // 清空心跳技术器
                    // 设置当前时间为最近一次时间错
                    if (currentTime - latestMinuteTimestamp > (60 * 1000)) {
                        latestMinuteHeartbeatRate = new AtomicLong(0L);
                        latestMinuteTimestamp = currentTime;
                    }
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
